package com.example.demo.config;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.demo.util.ResultEntity;

@ControllerAdvice
public class GlobalExceptionHandler {
	private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	@ResponseBody
	public ResultEntity<Void> MyExceptionHandle(MethodArgumentNotValidException exception) {
		BindingResult result = exception.getBindingResult();
		StringBuilder errorMsg = new StringBuilder();
		if (result.hasErrors()) {
			List<FieldError> fieldErrors = result.getFieldErrors();
			fieldErrors.forEach(error -> {
				LOGGER.info("field {},msg {}", error.getField(), error.getDefaultMessage());
				errorMsg.append(error.getDefaultMessage());
			});
		}
		return new ResultEntity<Void>("-1", errorMsg.toString());
	}
}
